package cn.ryanpenn.websocket;

import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.concurrent.TimeUnit;

/**
 * JettyClient
 */
public class JettyClient {

    public static final int PORT = 7080;
    private final String service_uri = String.format("ws://localhost:%d/service", PORT);

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static void main(String[] args) {
        new JettyClient().run();
    }

    void run() {
        WebSocketClient client = new WebSocketClient();
        SimpleEchoSocket socket = new SimpleEchoSocket();

        try {
            client.start();
            URI echoUri = new URI(service_uri);
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            client.connect(socket, echoUri, request);

            logger.info("Connecting to : %s%n", echoUri);

            socket.awaitClose(5, TimeUnit.SECONDS);

        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                client.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
